package com.zk.code.net;

import android.os.Environment;

import com.example.imgrecognition.Util.ArrayUtil;
import com.example.imgrecognition.Util.FileUploadFile;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.DatagramPacket;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class FileUploadClientHandler extends ChannelInboundHandlerAdapter {
	private int byteRead;
	private volatile int start = 0;
	private volatile int lastLength = 0;
	public RandomAccessFile randomAccessFile;
	private ByteBuf filebye;
	private String file_dir = Environment.getExternalStorageDirectory() + File.separator;

	public FileUploadClientHandler(ByteBuf filebye) {
		this.filebye = filebye;
	}


	protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket datagramPacket) throws Exception {
		//start = fileUploadFiles.getStarPos();
		try {
			ByteBuf byteBuf = datagramPacket.content();
			int len = byteBuf.readInt();
			int receivLen = byteBuf.readableBytes();
			byte[] bytes = new byte[byteBuf.readableBytes()];
			byteBuf.readBytes(bytes);
			if(receivLen < len){
				return;
			}else{
				if(receivLen<=60000){
					System.err.println(Arrays.toString(bytes));
					ctx.writeAndFlush(bytes);
				}else{
					int count = (int)receivLen/60000;
					List<byte[]> list = ArrayUtil.spliteArray(bytes,count);
					for(int i=0;i<list.size();i++){
						System.err.println(Arrays.toString(list.get(i)));
						ctx.writeAndFlush(list.get(i));
					}
				}
			}

		}catch (Exception e){

		}

	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		try {
			ByteBuf byteBuf = filebye;
			byte[] bytes = new byte[byteBuf.readableBytes()];
			byteBuf.readBytes(bytes);
			System.err.println("bytes-->"+Arrays.toString(bytes));
			ctx.writeAndFlush(bytes);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		//super.channelInactive(ctx);
	}

}
